﻿using System;
using System.Linq;
using System.Collections.Generic;
using Authentication.Data.Repository;
using Authentication.Model.Model;
using Authentication.Model.Interface;
namespace Authentication.Provider
{
    public class ApplicationProvider : GenericProvider, IApplicationProvider
    {
        public IEnumerable<Application> SearchApplications(out int totalRecord, string name = null, int pagesize = 0, int pageindex = 0, bool isOutTotal = true)
        {
            IEnumerable<Application> result = null;
            if (string.IsNullOrEmpty(name))
                result = repository.GetAll<Application>();
            else
                result = repository.Find<Application>(x => x.Name.ToUpper().Contains(name.Trim().ToUpper()));

            if (isOutTotal)
            {
                totalRecord = result.Count();
            }
            else
            {
                totalRecord = -1;
            }

            if (pagesize > 0 && pageindex >= 0)
            {
                result = result.Skip(pageindex * pagesize).Take(pagesize);
            }

            return result;
        }

        public Application RetrieveApplication(string applicationKey)
        {
            Guid key = Guid.Empty;
            if (Guid.TryParse(applicationKey, out key))
                return RetrieveApplication(key);
            else
                return repository.FindOne<Application>(x => x.Name.ToUpper() == applicationKey.Trim().ToUpper());
        }

        public Application RetrieveApplication(Guid applicationKey)
        {
            string application = applicationKey.ToString();
            return repository.FindOne<Application>(x => x.ApplicationKey.ToUpper() == application.Trim().ToUpper());
        }
    }
}
